package com.gxa.log.aop;

import com.alibaba.fastjson.JSON;
import com.gxa.log.cofig.IPUtil;
import com.gxa.log.cofig.OperateLogConfig;
import com.gxa.log.entity.ExcLog;
import com.gxa.log.entity.OperateLog;
import com.gxa.log.service.ExcService;
import com.gxa.log.service.OperService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
public class OperateAOP {
    /**
     * <p>
     * 项目启动时从命令行传入，例如：java -jar xxx.war --version=201902
     * </p>
     */
//    @Value("${version}")
    private String operateVer = "9999.999.99.9";

    @Autowired
    private OperService operationLogService;

    @Autowired
    private ExcService exceptionLogService;

    @Resource
    private IPUtil ipUtil;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.gxa.log.cofig.OperateLogConfig)")
    public void operateLogCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.gxa.*.*.*(..))")
    public void operateExceptionLogCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operateLogCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        OperateLog operatelog = new OperateLog();
        try {
//            operatelog.setOperId(UUIDUtil.getUid()); // 主键ID

            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperateLogConfig opLog = method.getAnnotation(OperateLogConfig.class);
            if (opLog != null) {
                String operateModule = opLog.OperateModule();
                String operateType = opLog.OperateType();
                String operateDesc = opLog.OperateDesc();
                operatelog.setOperModul(operateModule); // 操作模块
                operatelog.setOperType(operateType); // 操作类型
                operatelog.setOperDesc(operateDesc); // 操作描述
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            operatelog.setOperMethod(methodName); // 请求方法

            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);

            operatelog.setOperRequParam(params); // 请求参数
            operatelog.setOperRespParam(JSON.toJSONString(keys)); // 返回结果
//            operatelog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 请求用户ID
//            operatelog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 请求用户名称
            operatelog.setOperIp(ipUtil.getIP()); // 请求IP
            operatelog.setOperUrl(request.getRequestURI()); // 请求URI
            operatelog.setOperCreateTime(new Date()); // 创建时间
            operatelog.setOperVer(operateVer); // 操作版本
            operationLogService.insert(operatelog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operateExceptionLogCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        ExcLog excLog = new ExcLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
//            excLog.setExcId(UUIDUtil.getUid());
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            excLog.setExcRequParam(params); // 请求参数
            excLog.setExcMethod(methodName); // 请求方法名
            excLog.setExcName(e.getClass().getName()); // 异常名称
            excLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
//            excLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
//            excLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
            excLog.setExcUrl(request.getRequestURI()); // 操作URI
            excLog.setExcIp(ipUtil.getIP()); // 操作员IP
            excLog.setExcVer(operateVer); // 操作版本号
            excLog.setExcCreateTime(new Date()); // 发生异常时间

            exceptionLogService.insert(excLog);

        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

//    public static String getIpAddress(ServerHttpRequest request) {
//        HttpHeaders headers = request.getHeaders();
//        String ip = headers.getFirst("x-forwarded-for");
//        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
//        // 多次反向代理后会有多个ip值，第一个ip才是真实ip
//            if (ip.indexOf(",") != -1) {
//                ip = ip.split(",")[0];
//            }
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = headers.getFirst("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = headers.getFirst("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = headers.getFirst("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = headers.getFirst("X-Real-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddress().getAddress().getHostAddress();
//        }
//        return ip;
//    }
}
